var map;
var currentViewMapType = 2; // 当前航站楼
var allMaps = [
    {
        mapID: "1792818455411253249",
        license: "1c3f089d4a0c26b6294ef94712719fdb",
        name: "航站楼地图",
        mapType: 0
    },
    {
        mapID: "1792850316424290305",
        license: "86e5f7ea0fabccdabecfec6164cc7c31",
        name: "卫星厅地图",
        mapType: 1
    },
    {
        mapID: "1813117783302119425",
        license: "17a8f3db01aa030bf4f496d6d828c898",
        name: "融合地图",
        mapType: 2,
    },
    {
      mapID: "1818221227872587777",
      license:"77c9e36ae2dc9aae323a621a68c2b5a2",
      name: "室内外一体化",
      mapType: 3,
    }
]
var floorInfos = []; //楼层相关信息
var scrollFloorControl; //导航器
/* 根据楼层level id获取楼层name */
function getFloorNameByGid(level, buildingId) {
    var floorInfo
    if (buildingId) {
        floorInfo = map.getBuilding(buildingId).getFloorInfos();
    } else {
        floorInfo = map.getFloorInfos();
    }
    var floorName = floorInfo.find(function (item) {
        return item.level === level;
    }).name;
    return floorName;
}
// 地图对象创建
window.onload = function () {
    changeAnotherMap();
}

function InitMap(opts = {}) {
    // 地图初始化设置参数
    var options = {
        container: document.getElementById('fengmap'),
        appName: '商场导览端样例的导览端微程序',
        key: '36344769ec20478ffa7944380d45b217',
        mapID: allMaps[currentViewMapType].mapID,
        themeID: '1813128535299932162',
        license: allMaps[currentViewMapType].license,
        tile: false,			            //是否分层加载,默认值:true
        preLoad: true,
        // level: 3,
        mapZoom: 15,
        zoomRange: [15, 23],
        // enabledPanRange: true,
        // panRangeValue: {
        //   center: {
        //     x: 12613420.377354909,
        //     y: 2642623.57332401
        //   },
        //   radius: 0.1
        // },
        tiltAngle: 30,
        maxTiltAngle: 360, // 最大倾斜角度 默认值: 90
        minTiltAngle: 0, //最小倾斜角度 默认值: 30
        nonFocusAlphaMode: true,
        // nonFocusAlpha: 0.1,
        // visibleLevels: [1, 2, 3, 4, 5, 6, 7],
        hideList: {
            [fengmap.FMType.LABEL_LAYER]: {
                typeIDs: [170001, 170002, 170003, 170004, 170005, 170006, 400107],
            },
        },
        ...opts
    }
    const promise = new Promise((resolve, reject) => {
        if (map != null) {
            map.dispose();
            map = null;
        }
        map = new fengmap.FMMap(options);
        map.on('loaded', function () {
            animateInitMap()
            console.log("地图初始化完成！", $parent_this);
            resolve('地图初始化完成！');
        });
        map.on('click', handleMapEvent)
    });
    return promise;
};

function changeAnotherMap() {
    scrollFloorControl && scrollFloorControl.remove();
    InitMap().then(loadedInitFun)
}
function animateInitMap() {
    // map.setDevicePixalRatio(1);
    let animation = map.autoRotate({
        duration: 15
    });
    map.setZoom({
        zoom: 15,
        animate: true,
        duration: 3,
        finish: () => {
            animation.finish(); // 强制完成
            map.setTilt({
                tilt: 45,
                animate: true,
                duration: 2,
                finish: () => {
                }
            })
        },
    })
}

function loadedInitFun() {
    initMapSearch();
    getMapAttributes();//地图属性
    initFloorControl();//楼层导航
    //初始化路径分析类
    initNaviRouter(() => {
        sortOutPointBelongMap();
    });
}

// 地图点击事件
function handleMapEvent(e) {
    e = {
        ...e,
        location: mapXyToLatlngCoords({
            ...e.coords
        })
    }
    console.log(e);
    let isCrittur = e.targets.find(f => f._extra)
    if (isCrittur && isCrittur.nodeType) {
        handelCritturEvent(isCrittur);
    }
}

function handelCritturEvent(e) {
    if (e.nodeType === 'riderPoint') {
        handleRiderMarkerEvent(e)
    }
    if (e.nodeType === 'riderLine') {
        changeLineColor(e)
    }
}


function initMapSearch() {
    if (!serveSetting.canSearch) return;
    document.getElementById("search-panel").style.display = "block";
    searchAnalyser = new fengmap.FMSearchAnalyser({
        map
    }, () => { })
}
// 触发地图搜索服务
function searchMapPoint() {
    const keyword = document.getElementById("searchInput").value;
    const searchRequest = new fengmap.FMSearchRequest();
    searchRequest.addCondition({
        keyword: {
            text: keyword,
            fuzzy: true, // 模糊查询
        }
    });

    searchAnalyser.query(searchRequest, (result) => {
        const newResult = result
            .filter((item) => item.name !== undefined)
            .map((item) => {
                const { lat, lng } = mapXyToLatlngCoords({
                    x: item.center.x,
                    y: item.center.y
                });
                return {
                    ...item,
                    lat,
                    lng
                };
            });
        console.log(newResult);
    });
}
// 初始化楼层导航器
function initFloorControl() {
    var scrollFloorCtlOpt = {
        position: fengmap.FMControlPosition.RIGHT_TOP,
        floorButtonCount: 5,
        offset: {
            // x: -630,
            // y: 400
        },
        viewModeControl: true,
        floorModeControl: true,
        needAllLayerBtn: true
    };
    scrollFloorControl = new fengmap.FMToolbar(scrollFloorCtlOpt);
    // let newElement = document.createElement("div");
    // newElement.className = `fm-view fm-view-st-${currentViewMapType}`;
    // newElement.title = `切换${allMaps[currentViewMapType ? 0 : 1].name}`
    // newElement.onclick = function (e) {
    //     if (currentViewMapType) {
    //         currentViewMapType = 0;
    //     } else {
    //         currentViewMapType = 1;
    //     }
    //     e.target.className = `fm-view fm-view-st-${currentViewMapType}`
    //     console.log(allMaps[currentViewMapType].mapID);
    //     changeAnotherMap();
    // }
    let newElement2 = document.createElement("div");
    newElement2.className = `fm-view fm-view-reload-page`;
    newElement2.title = `刷新地图`
    newElement2.onclick = function (e) {
        location.reload();
    }
    scrollFloorControl.addTo(map)
    let el = document.querySelector(".fm-control-groups");
    // el.insertBefore(newElement, el.firstChild)
    el.insertBefore(newElement2, el.firstChild)
}
function moveControl(fold) {
    console.log(fold);
    // fm-view-move
    let el = document.querySelector(".fm-control-groups");
    if (fold) {
        el.classList.add("fm-view-move");
    } else {
        el.classList.remove("fm-view-move");
    }
}
function setMapLevel(level) {
    return new Promise((resolve) => {
        map.setLevel({
            animate: true,
            level,
            duration: 0.3,
            finish: resolve,
        });
    });
}

function setMapZoom(zoom) {
    return new Promise((resolve) => {
        map.setZoom({
            zoom,
            animate: true,
            finish: resolve,
        });
    });
}

function setMapCenter(coords) {
    return new Promise((resolve) => {
        map.setCenter({
            animate: true,
            duration: 0.5,
            ...coords,
            finish: resolve,
        });
    });
}

function mapGo(e) {
    const { level, lng, lat } = e;
    catchLevelPossibleException();
    const mapCenterCoords = latlngToMapXyCoords({ lng: lng, lat: lat });
    const currentLevel = map.getLevel();
    let promiseChain;
    if (level && currentLevel !== level) {
        promiseChain = setMapLevel(level);
    } else {
        promiseChain = Promise.resolve();
    }
    promiseChain
        .then(() => setMapZoom(19))
        .then(() => setMapCenter(mapCenterCoords))
        .catch((error) => {
            console.error("Error setting map center:", error);
        });
}
// 捕捉可能楼层存在异常的情况
function catchLevelPossibleException(level) {
    if (level && !floorInfos.some(s => s.level == level)) {
        throw new Error(`无法定位到的地图图层--> ${level} `)
    }
}

// 初始化地图的一些属性信息
function getMapAttributes() {
    floorInfos = map.getFloorInfos();
    console.log("floorInfos", floorInfos, JSON.stringify(floorInfos));
}
